// signin.js

var signin = {

	state: {
		//*date: (new Date()).formatDate(),
		date: (new Date('2011-09-03')).formatDate(),
		emp_id: null
	},

	funcs: {
		calc: function(e) {
			var el = (e instanceof Event) ? e.target : e;

			var pre = Post.pre(e.target);
			var idx = Post.idx(e.target);
			var dir = Post.col(e.target).match(/^(.*)(_dt|_tm|_ts)$/)[1];
			//-console.log( 'starting signin.funcs.calc on '+e.target.name+' - '+dir );

			// get parts and create new date
			//-console.log( "Post.colValue("+pre+","+idx+","+dir+"_tm)" );
			var tmStr = Post.colValue(pre,idx,dir+'_tm');
			//-console.log( 'tmStr = '+tmStr );
			if( tmStr && tmStr.length ) {
				try{ tmStr = util.fixTime(tmStr); }
				catch(e) { util.nonblockAlert( "Illegal Time Format: "+tmStr ); return false; }
				Post.colSetValue(pre,idx,dir+'_tm',tmStr);
			}
			//-console.log( 'time: '+Post.colValue(pre,idx,dir+'_tm') );
			var dtStr = Post.colValue(pre,idx,dir+'_dt');
			if( dtStr && dtStr.length ) {
				try{ dtStr = util.fixDate(dtStr); }
				catch(e) { util.nonblockAlert( "Illegal Date Format: "+dtStr ); return false; }
				Post.colSetValue(pre,idx,dir+'_dt',dtStr);
			}
			//-console.log( 'date: '+Post.colValue(pre,idx,dir+'_dt') );

			// must have both to set timestamp
			if( tmStr && tmStr.length && dtStr && dtStr.length ) {
				var ts = new Date( dtStr + ' ' + tmStr );
				Post.colSetValue(pre,idx,dir+'_ts',ts.formatDT());
			}
			else	Post.colSetValue(pre,idx,dir+'_ts','');
			//-console.log( 'timestamp: '+Post.colValue(pre,idx,dir+'_ts') );

			return true;
		},
		// init ts if empty
		initDt: function(e) {
			if( e.target.value == ''  ) {
				e.target.value = (Post.col(e.target))=='from_dt' ? (new Date()).formatDate() : (new Date()).formatTime();
				signin.funcs.calc(e);
			}
		},
		// set ts to current time on double click
		clickDt: function(e) {
			e.target.value = (Post.col(e.target))=='from_dt' ? (new Date()).formatDate() : (new Date()).formatTime();
			signin.funcs.calc(e);
			// init change event from here
			var change = document.createEvent("Event");
			change.initEvent('change',true,true);
			e.target.dispatchEvent(change);
		}
	},

	// normal signin
	signin: function( date ) {
		util.popout();

		//-console.log( 'signin: date='+date+', signin.state.date='+signin.state.date );
		if( date && !(date instanceof Event) ) signin.state.date = date;

		var rd = signin.rd = new Render( 'rd', {rcds:[{sgn_dt:signin.state.date}],
			formRender: function() { return rd.form( 'rel', '.l', rd.div( 'tup',
				rd.b('for Date'), rd.date( 'sgn_dt', 'datatype:date', 's.marginLeft:5px', 's.width:92px', 'e.change:resetDate' ),
				rd.h1( 'Daily Sign In', 's.marginLeft:10%', 's.marginTop:0', 's.MarginBottom:0', 's.display:inline-block' )
			) ) },
			resetDate: function() {
				var dt = rd.domItemValue('0','sgn_dt');
				console.log( 'reset for '+dt );
				signin.state.date = dt;
				signin.signin();
			}
		} );

		var sgn = signin.sgn = new Render( 'sgn', {extraNo:1, select:{key:"date(from_ts)='"+signin.state.date+"'"}, orderBy:'emp_nm',
			dfltRcd: {from_dt: signin.state.date, thru_dt: signin.state.date },
			formRender: function() { 
				return sgn.form( 'rel', 'update:col', 'request:row', 'embold:row', sgn.table(
				sgn.thead( sgn.tr( sgn.ths( '', 'Employee', 'Sign In', 'Sign Out',
						'2:Entered By=insert_login,insert_ts', '2:Changed By=update_login,update_ts' ) ) ),
				sgn.tbody( sgn.rows() ) ) ) },
			rowRender: function() { return sgn.tr( 'tup', {update:((sgn.r('sgn_id'))?'col':'row')},
				sgn.td( '.c', sgn.span( {'e.mouseover':sgn.hover}, '.embold z08 pl pr', 'GO' ) ),
				sgn.td(
					sgn.hidden('emp_id'),
					sgn.text( 'emp_nm', 'lookup:emp_id' ) ),
				sgn.td(
					sgn.hidden('from_ts'), sgn.hidden('from_dt'),
					sgn.time( 'from_tm', 'e.focus:signin.funcs.initDt', 'e.dblclick:signin.funcs.clickDt' ) ),
				sgn.td(
					sgn.hiddens('thru_ts','thru_dt'),
					sgn.time( 'thru_tm', 'e.dblclick:signin.funcs.clickDt', 'e.change:signin.funcs.calc' )),
				sgn.td( '.z08', sgn.r('insert_login') ),
				sgn.td( '.z08', sgn.r('insert_ts') ),
				sgn.td( '.z08', sgn.r('update_login') ),
				sgn.td( '.z08', sgn.r('update_ts') )
				) },
			contentRender: signin.signin,

			// hover menu
			hover: function(e) {
				
				var tup = e.target.ancestorByAttribute('tup');
				var idx = tup.getAttribute('tup').split(':')[1];
				var changed = ( Post.changeCt(tup) > 0 );
				var pkval = tup.getAttribute(tup.getAttribute('tup')+':pkval');
				var emp_id = sgn.domItemValue(idx,'emp_id');
				//-console.log( 'hover: tup='+tup+', change='+changed );

				// build hover - not new
				if( pkval ) util.hover.init( e.target.parentNode, rd.ul(
						((changed)? rd.li( rd.a( '#', sgn.update, 'SAVE CHANGES' ) ) : null ),
						rd.li( rd.a( '#', sgns, 'Recent Signins' ) ),
						rd.li( rd.a( '#', svcs, 'Recent Services' ) ),
						rd.li( rd.a( '#', sgn.dlx, 'Delete Signin' ) )) );
				// insert - virgin row
				else if( !changed ) util.hover.init( e.target.parentNode, rd.ul( 'Enter changes', 'then SAVE' ) );
				// insert - changed
				else util.hover.init( e.target.parentNode, rd.a( '#', function(e) {
					Post.update( {e:e,render:sgn,update:'row',request:'row',el:e.target.ancestorByAttribute('tup')} );
				}, 'SAVE CHANGES' ) );

				function sgns(e) { signin.recent(emp_id,signin.signin) };
				function svcs(e) { /* todo */ };
			},
			} );

		// sigin sheet
		Render.replaceAll( contentDom, rd.formRender(), sgn.formRender() );

		// change base date for page
		function dateRefresh(e) {
			alert( e.target.value );
		};
	},

	// param will be Event or emp_id
	recent: function(emp_id,doneFunc) {

		if( emp_id ) signin.state.emp_id = emp_id;

		// header - customer name
		var rt = signin.rt = new Render( 'rt', {dd:'sgn', select:{fks:['emp_id'],key:'emp_id='+signin.state.emp_id},
			formRender: function() { return rt.form( 'rel', '.l', 'update:none', rt.div( 'tup', '.nbk',
				rt.b('for Employee'), rt.select( 'emp_id', {value:signin.state.emp_id, enum:rt.fks('emp_id'), 'e.change':function(e) {
					signin.state.emp_id = e.target.value;
					console.log( 'reset for '+signin.state.emp_id );
					Render.replaceAll( document.getElementById('sgns'), sgns() );
				} } ),
				rt.h1( 'Daily Sign In', 's.marginLeft:10%', 's.marginTop:0', 's.MarginBottom:0', 's.display:inline-block' ),
				((doneFunc) ? rt.a('#',doneFunc,'.z12',' \u00a0 \u003c\u003cBACK') : null )
			) ) }
		} );

		Render.replaceAll( contentDom, rt.formRender(), rt.div( '#sgns', sgns() ) );

		// list of signins for one employee
		function sgns( emp_id ) {

			emp_id = emp_id || signin.state.emp_id;

			var rct = signin.rcd = new Render( 'rct', {dd:'sgn', extraNo:1, orderBy:'from_ts desc',
					select:{key:"emp_id="+signin.state.emp_id},
					dfltRcd:{emp_id:signin.state.emp_id},
				formRender: function() { return rct.form( 'rel',  'update:row', 'require:row-form', 'embold:row',
					rct.table( 's.overflow:auto',
						rct.thead( rct.tr( rct.ths( '', 'Date', 'Sign In', 'Sign Out', '2:Created=insert_login,insert_ts',
								'2:Updated=update_login,update_ts' ) ) ),
						rct.tbody( rct.rows() ) ) ) },
				rowRender: function() { return rct.tr( 'tup',
					rct.td( '.c', rct.span( {'e.mouseover':rct.hover}, '.embold z08 pl pr', 'GO' ) ),
					rct.td( rct.hidden('emp_id'),
						rct.date( 'from_dt', 'e.dblclick:signin.funcs.clickDt', {'e.change':change} ) ),
					rct.td(
						rct.hidden('from_ts'),
						rct.time( 'from_tm', 'e.dblclick:signin.funcs.clickDt', {'e.change':change} ) ),
					rct.td(
						rct.hidden('thru_ts'),
						rct.time( 'thru_tm', 'e.dblclick:signin.funcs.clickDt', {'e.change':change} ) ),
					rct.td( '.z08 r pl', rct.r('insert_login') ),
					rct.td( '.z08', rct.r('insert_ts') ),
					rct.td( '.z08 r pl', rct.r('update_login') ),
					rct.td( '.z08', rct.r('update_ts') ) ); },

				// hover menu
				hover: function(e) {
					
					var tup = e.target.ancestorByAttribute('tup');
					var pre = tup.getAttribute('tup').split(':')[0];
					var idx = tup.getAttribute('tup').split(':')[1];
					var changed = ( Post.changeCt(tup) > 0 );
					var pkval = tup.getAttribute(tup.getAttribute('tup')+':pkval');
					var from_dt = Post.colValue(pre,idx,'from_dt');

					// build hover - not new
					if( pkval ) util.hover.init( e.target.parentNode, rct.ul(
							((changed)? rct.li( rct.a( '#', 'update', 'SAVE CHANGES' ) ) : null ),
							rct.li( rct.a( '#', function(e) { signin.signin(from_dt); }, 'All for Date' ) ),
							rct.li( rct.a( '#', rct.dlx, 'Delete Signin' ) )) );
					// insert - virgin row
					else if( !changed ) util.hover.init( e.target.parentNode, rct.ul( 'Enter changes', 'Only Save', 'When New Date' ) );
					// insert - changed
					else util.hover.init( e.target.parentNode, rct.a( '#', 'update', 'SAVE CHANGES' ) );
				}

				} );
			
			function change(e) {
				// prevent re-entry
				console.log( 'rct change: '+e.change );
				if( e.changeCt ) return;
				e.changeCt = (e.changeCt==undefined) ? 0 : e.changeCt+1;
				var el = Post.colDom( Post.pre(e.target), Post.idx(e.target), Post.col(e.target).substr(0,5)+'ts' );
				console.log( 'rct.change, el='+e.target.name+', change='+e.changeCt );
				signin.funcs.calc(e);
				// manually post time, and prevent upstream post call
				if( Post.col(e.target)!='from_dt' ) {
					Post.update( {e:e, el:el, update:'col', request:'row', render:rct} );
					e.stopPropagation();
				}
			};

			return rct.formRender();

		}
	}
}
